package com.xbk.seckill.order.application.message;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.xbk.seckill.common.constants.SeckillConstants;
import com.xbk.seckill.common.model.message.ErrorMessage;
import com.xbk.seckill.order.application.service.SeckillOrderService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 订单微服务监听异常消息
 *
 * @author xiexu
 * @date 2025/2/26 21:06
 */
@Slf4j
@Component
@RocketMQMessageListener(consumerGroup = SeckillConstants.TX_ORDER_CONSUMER_GROUP, topic = SeckillConstants.TOPIC_ERROR_MSG)
public class OrderErrorMessageListener implements RocketMQListener<String> {

    @Autowired
    private SeckillOrderService seckillOrderService;

    /**
     * 消费消息
     * 
     * @param message 消息
     */
    @Override
    public void onMessage(String message) {
        log.info("onMessage|秒杀订单微服务开始消费消息:{}", message);
        if (StrUtil.isEmpty(message)) {
            return;
        }
        ErrorMessage errorMessage = this.getErrorMessage(message);
        // 删除数据库中对应的订单信息
        seckillOrderService.deleteOrder(errorMessage);
    }

    /**
     * 转换消息对象
     * 
     * @param msg 消息
     * @return 错误信息
     */
    private ErrorMessage getErrorMessage(String msg) {
        JSONObject jsonObject = JSONObject.parseObject(msg);
        String txStr = jsonObject.getString(SeckillConstants.MSG_KEY);
        return JSONObject.parseObject(txStr, ErrorMessage.class);
    }
}